#!/bin/sh

if [ $# != 3 ]; then
    echo "Usage: $0 <master_ip> <authzcode> <path_to_bind_chroot>"
    exit 1
fi

MASTERIP=$1
AUTHZCODE=$2
BINDCHROOT=$3


#1. init user(xdslave) enviroment 
#===============================
rm -rf /home/xdslave
userdel xdslave
useradd xdslave -g named -s /sbin/nologin -d /home/xdslave
rm -rf /home/xdslave
mkdir -p /home/xdslave/{.ssh,prog}
mkdir -p /home/xdslave/named/{log,etc/{acl,view,dynamic}}

touch /home/xdslave/.ssh/known_hosts
ssh-keygen -t dsa -f /home/xdslave/rsync-key -N ""

#2. register to Master 
#================================
echo "xdreg slave -m $MASTERIP -a $AUTHZCODE"
xdreg slave -m $MASTERIP -a $AUTHZCODE
if [ $? -ne 0 ]; then
exit 1
fi


#3. sync program and configuration
#=============================== 
mv ~/.ssh/known_hosts ~/.ssh/known_hosts.bak
cp /home/xdslave/.ssh/known_hosts ~/.ssh/known_hosts

rsync -avz -e 'ssh -i /home/xdslave/rsync-key' xbaydns@$MASTERIP:/home/xbaydns/slave/prog /home/xdslave
rsync -avz -e 'ssh -i /home/xdslave/rsync-key' xbaydns@$MASTERIP:/home/xbaydns/slave/slave.conf /home/xdslave/slave.conf

mv ~/.ssh/known_hosts.bak ~/.ssh/known_hosts


#4. setup up cron
==================================
crontab -u xdslave -l >/home/xdslave/old_crontab 2>/dev/null
crontab -u xdslave /home/xdslave/prog/crontab
crontab -u root -l |grep -v ReloadNamed>/tmp/root_crontab 2>/dev/null
echo "*/5 * * * * /home/xdslave/prog/ReloadNamed.sh">>/tmp/root_crontab
crontab -u root /tmp/root_crontab


#5. prepare bind's chroot
#-----------------------
mkdir -p $BINDCHROOT/{etc/{acl,view,dynamic},dev,var/{run,dump,stats,log}}
touch $BINDCHROOT/var/log/named.log
touch $BINDCHROOT/var/log/query.log

rm -f $BINDCHROOT/dev/{random,zero,null}
mknod $BINDCHROOT/dev/random c 1 8
mknod $BINDCHROOT/dev/zero c 1 5
mknod $BINDCHROOT/dev/null c 1 3


#6.set envionment variables
#==========================
echo "\
XBAYDNS_CHROOT_PATH=$BINDCHROOT
XBAYDNS_BIND_CONF=/etc
XBAYDNS_BIND_START=/usr/local/sbin/named
XBAYDNS_BIND_USER=named
export PATH XBAYDNS_CHROOT_PATH XBAYDNS_BIND_CONF XBAYDNS_BIND_START XBAYDNS_BIND_USER
"|tee /home/xdslave/xdenv

chmod +x /home/xdslave/xdenv
source /home/xdslave/xdenv
id named || useradd named -s /sbin/nologin
xdinitbind slave $MASTERIP

rm -f /etc/rndc.key
ln -s $BINDCHROOT/etc/rndc.key /etc/
rndc reload
chown -R named:named $BINDCHROOT
chmod -R 770 $BINDCHROOT
chown -R xdslave:named /home/xdslave
chmod -R 700 /home/xdslave


#7. message
#=============================
MYNAME=`cat /home/xdslave/myname`
echo "\



XBayDNS(enabled slave) installed successfully!
MASTER    :$MASTERIP
SLAVE CODE:$MYNAME
HOME      :/home/xdslave

The next thing you may do:
.  Start named server and make sure named running normally
   #/usr/local/sbin/named -t $XBAYDNS_CHROOT_PATH -u named
   #tail -f /var/log/messages

"
